package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /**
     * admin 登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDTO dto) {
        //参数校验
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "无效参数");
        }
        //根据用户名查找用户信息
        AdUser aduser = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (aduser == null) {
            CustException.cust(AppHttpCodeEnum.ADMING_CHANNEL_NOT_EXIST, "用户不存在");
        }
        //对比输入的密码和数据库中的密码是否一致
        String password = dto.getPassword();
        String inputPwd = DigestUtils.md5DigestAsHex((password + aduser.getSalt()).getBytes());
        if (!inputPwd.equals(aduser.getPassword())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "密码不正确");
        }
        if (aduser.getStatus() != 9) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"用户状态异常，请联系管理员");
        }
        //修改最近的登录时间
        aduser.setLoginTime(new Date());
        this.updateById(aduser);
        //颁发token
        String token = AppJwtUtil.getToken(aduser.getId().longValue());
        //返回结果
        AdUserVO adUserVO = new AdUserVO();
        BeanUtils.copyProperties(aduser,adUserVO);
        Map map = new HashMap();
        map.put("token", token);
        map.put("user", adUserVO);
        return ResponseResult.okResult(map);
    }
}
